

<template>
  <div id="main" style="width: 400px; height: 400px">图表1</div>
</template>

<script>
// 第一步引入组件
import * as echarts from "echarts";
import axios from "axios";
import { onMounted } from "vue";
export default {
  // 第二步使用vue3 中的setup  onMounted
  name: "one",
  setup() {
    //vue3生命周期函数
    onMounted(() => {
      datainit();
    });
    // 第三步定义要用到的变量
    let dataAll = [];
    let bool = false;
    //第四步初始化方法
    const datainit = () => {
      let url = "/api/total";
      //axios请求后端数据；
      axios.get(url).then((res) => {
        console.log(res);
        //定义一个变量方便数据传导
        let data = res.data;
        //第五步相同省份求和
        for (let i in data) {
          for (let j in dataAll) {
            if (dataAll[j].name == data[i].region) {
              dataAll[j].value = dataAll[j].value + data[i].priceSale;
              bool = true;
            }
          }
          if (!bool) {
            let map = { name: data[i].region, value: data[i].priceSale }; //第六步将自己的数据名称和值换成自己的
            dataAll.push(map); //通过map方法实现，把map的数据给到dataAll
          }
          bool = false;
        }
        dataAll.sort((a, b) => b.value - a.value); //降序  求最高的五个省份的消费额
        // dataAll.sort((a, b) => a.value - b.value); //升序     求最低的五个省份的消费额
        dataAll = dataAll.slice(0, 5); //控制前几的消费额

        let citys = [];
        let buys = [];
        for (let j in dataAll) {
          citys.push(dataAll[j].name);
          buys.push(dataAll[j].value);
        }
        console.log(citys);
        console.log(buys);
        init(citys, buys);
      });
    };
    const init = (citys, buys) => {
      let option = {
        title: {
          text: "2023年消费额最高的五个地区",
        },
        xAxis: {
          data: citys,
          name: "省份",
        },
        yAxis: {
          name: "消费额",
        },
        series: [
          {
            data: buys,
            type: "bar",
          },
        ],
      };
      let myChart = echarts.init(document.getElementById("main"));
      myChart.setOption(option);
    };
  },
};
</script>